<?php

namespace App\Admin\Controllers;

use App\Services\CustomerGroupService;
use App\Support\Components;
use Slowlyo\OwlAdmin\Controllers\AdminController;

/**
 * 客户分组管理
 *
 * @property CustomerGroupService $service
 */
class CustomerGroupController extends AdminController
{
	protected string $serviceName = CustomerGroupService::class;

	public function list()
	{
		$crud = $this->baseCRUD()
			->filterTogglable(false)
			->headerToolbar([
				$this->createButton('dialog'),
				...$this->baseHeaderToolBar()
			])
			->columns([
				amis()->TableColumn('id', 'ID')->sortable(),
				amis()->TableColumn('customer_name', '客户名称'),
				amis()->TableColumn('nodecount', '节点数量'),
				amis()->TableColumn('remark', '备注'),
				amis()->TableColumn('bd_uid.name', '业务负责人')->sortable(),
				amis()->TableColumn('created_at', admin_trans('admin.created_at'))->type('datetime')->sortable(),
				amis()->TableColumn('', '操作')->type('operation')->buttons([
					// 添加一个查看流量的按钮
					$this->flowStatisticsButton(),
					$this->rowEditButton('dialog'),
					$this->rowDeleteButton(),
				]),
			]);

		return $this->baseList($crud);
	}

	/**
	 * 流量统计按钮
	 */
	protected function flowStatisticsButton()
	{
		return amis()->DialogAction()
			->label('查看流量')
			->icon('fa-solid fa-chart-line')
			->level('info')
			->dialog(
				amis()->Dialog()
					->title('${customer_name}流量统计 包含${nodecount}个节点')
					->size('full')
					->body([
						// 循环显示各个端口的流量图表
						amis()->Grid()
						->columns([
							amis()->Each()
								->type('each')
								->source('${node_name}')
								->items( 
									// 这里显示循环内的具体内容 每个内容一个panl 然后分左右两列
									amis()->Panel()->body([
										//左侧内容
										amis()->Grid()->columns([
											// 左侧节点详细信息
										amis()->GridColumn()->lg(4)->body(
												amis()->Form()->mode('horizontal')->submitText()->title()
												->initApi('/node_management/${item}?_action=getData')
												->body([
													amis()->StaticExactControl('name', '${customer_name}:')->className('m-0'),
													amis()->StaticExactControl('customer_bus.sign_company.company_name', '签约公司:')->className('m-0'),
													amis()->StaticExactControl('customer_bus.billing_type', '计费方式:')->className('m-0'),
													amis()->StaticExactControl('customer_bus.bandwidth', '出口带宽:')->className('m-0')->tpl('${export_bandwidth}G'),
													amis()->StaticExactControl('customer_bus.guarantee_bandwidth', '保底:')->className('m-0'),
													amis()->StaticExactControl('customer_bus.operator.name', '操作人:')->className('m-0'),
													amis()->StaticExactControl('customer_bus.created_at', '添加时间:')->className('m-0'),
													amis()->StaticExactControl('node_remark', '备注:')->className('m-0'),
													// 
													amis()->StaticExactControl('remark', '本月故障记录')->className('m-0')->event('click', '/fault_record?customer_group_id=${id}'),
													amis('control')->label('下载数据')->body([
														amis()->GroupControl()->body([
															
															// 改为直接请求api接口 /flowscharts 带下载参数 actions=download
															amis()->Button()->label('下载月95数据')->level('primary')->onEvent([
																'click' => [
																	'actions' => [
																		[
																			'actionType' => 'download',
																			'api' => [
																				'url' => '/flowscharts',
																				'method' => 'get',
																				'responseType' => 'blob',
																				'data' => [
																					'actions' => 'download',
																					'id' => '${id}',
																					'type' => 'node',
																					'month' => '${month}',
																					'dataType' => '1000'
																				]
																			]
																		]
																	]
																]
															]),
														

															amis()->DrawerAction()->label('下载日95数据')->level('primary')->drawer(
																amis()->Drawer()->closeOnOutside()->title('下载日95数据')->size('lg')
																->body(
																	amis()->Page()
																		
																		->body([
																			amis()->Form()
																				->id('day95Form')
																				->initApi('/tools/get_days_of_month?month=${month}')
																				->submitText() // 隐藏提交按钮
																				->title() // 隐藏标题
																				->body([
																					amis()->MonthControl()
																						->name('month')
																						->label('选择月份')
																						->value(date('Y-m', strtotime('last month')))
																						->className('mb-3')
																						->onEvent([
																							'change' => [
																								'actions' => [
																									[
																										'actionType' => 'reload',
																										'target' => 'day95Form',
																										'args' => ['month' => '${month}']
																									]
																								]
																							]
																						]),
																						amis()->Each()
																						->source('${days}')
																						->items(
																							amis()->Panel()
																								->className('mb-3 day-panel')
																								->data([
																									'date' => '${date}'
																								])
																								->bodyClassName('p-0')
																								->title('${date} 95流量图')
																								->body(
																									amis()->Card()->className('day95-chart')
																									->style([
																										'border' => 'none',
																									])
																									->body([
																										Components::make()->trafficChart('day95', '', '${item}')
																											->id('day95Chart_${date}')
																											->showDownload(true)
																									])
																								)
																								->attr('data-date', '${date}')
																									),
																									
																					amis()->ButtonToolbar()->className('mb-3')->buttons([
																						amis()->Button()
																							->label('批量下载所有图表')
																							->level('primary')
																							->onEvent([
																								'click' => [
																									'actions' => [
																										[
																											'actionType' => 'custom',
																											'script' => '
																												// 确保JSZip已加载
																												if (typeof JSZip === "undefined") {
																													alert("JSZip库未加载，请刷新页面重试");
																													return;
																												}
																												
																												// 等待一小段时间确保图表已完全渲染
																												setTimeout(function() {
																													const charts = document.querySelectorAll(".day95-chart canvas");
																													console.log("找到图表数量:", charts.length);
																													
																													if (charts.length === 0) {
																														alert("没有找到图表，请确保图表已加载完成");
																														return;
																													}
																													
																													const zip = new JSZip();
																													const folder = zip.folder("日95流量图表");
																													const promises = [];
																													
																													charts.forEach((canvas, index) => {
																														try {
																															const dataUrl = canvas.toDataURL("image/png");
																															const base64Data = dataUrl.replace(/^data:image\/png;base64,/, "");
																															
																															// 获取日期信息
																															const panel = canvas.closest(".day-panel");
																															const date = panel ? panel.getAttribute("data-date") || 
																																panel.querySelector(".cxd-Panel-title").textContent.trim() : 
																																`图表_${index + 1}`;
																															
																															const fileName = `${date}_95流量图.png`;
																															folder.file(fileName, base64Data, {base64: true});
																															console.log("添加文件:", fileName);
																															promises.push(Promise.resolve());
																														} catch (e) {
																															console.error("处理图表出错:", e);
																														}
																													});
																													
																													Promise.all(promises).then(() => {
																														zip.generateAsync({type: "blob"}).then(function(content) {
																															const link = document.createElement("a");
																															link.href = URL.createObjectURL(content);
																															link.download = "日95流量图表.zip";
																															link.click();
																															console.log("下载完成");
																														}).catch(function(error) {
																															console.error("生成ZIP文件失败:", error);
																															alert("生成ZIP文件失败，请查看控制台了解详情");
																														});
																													});
																												}, 1000);
																											'
																										]
																									]
																								]
																										]),
																						// 下载所有数据
																						amis()->Button()->label('下载所有数据')->level('primary')
																						->actionType('url')
																						->url(url('/admin-api/flowscharts?actions=batch_download&type=node&month=${month}&dataType=1000&id=${id}'))
																						->blank(true)
																					]),
																					
																				])
																		])
																)
															),

															amis()->DrawerAction()->label('下载日峰值数据')->level('success')->drawer(
																amis()->Drawer()->closeOnOutside()->title('下载日峰值数据')->size('lg')
																->body($this->form())
															),

														]),
													]),
												]),
											),
										//右侧内容
										amis()->GridColumn()->lg(8)->body(
											amis()->Form()
												->id('flowchartForm')
												->wrapWithPanel(false)
												->title('')
												->submitText('')
												->data([
													'month' => date('Y-m', strtotime('last month')),
													'dataType' => '1000'
												])
												->body([
													amis()->Grid()->className('mb-4')->columns([
														amis()->GridColumn()->md(2)->body(
															// 添加月份筛选
															amis()->MonthControl()
																->name('month')
																->label('')
																->value(date('Y-m', strtotime('last month')))
																->onEvent([
																	'change' => [
																		'actions' => [
																			[
																				'actionType' => 'reload',
																				'componentId' => 'flowChart_${item}',
																				'args' => ['month' => '${month}']
																			]
																		]
																	]
																])
														),
														amis()->GridColumn()->md(2)->body(
															amis()->ButtonGroupControl()
																->labelAlign('right')
																->name('dataType')
																->label('')
																->btnActiveLevel('danger')
																->value('1000')
																->onEvent([
																	'change' => [
																		'actions' => [
																			[
																				'actionType' => 'reload',
																				'componentId' => 'flowChart_${item}',
																				'args' => ['dataType' => '${dataType}']
																			]
																		]
																	]
																])
																->options([
																	['label' => '1000', 'value' => '1000'],
																	['label' => '1024', 'value' => '1024'],
																])
														)
												]),
											// 流量图表
											amis()->Card()->body([
												Components::make()->trafficChart('node','', '${item}')
													->className('flowChart_${item}')
													->id('flowChart_${item}')
											])
												]),
											
										)
										]),
									])
								)
						])
					])
			);
	}

	public function form($isEdit = false)
	{
		return $this->baseForm()->body([
			amis()->TextControl('customer_name', '客户名称'),
			amis()->SelectControl('node_name', '节点名称')
				->multiple(true)
				->searchable(true)
				->source('/node_management?_action=getData')
				->labelField('name')
				->valueField('id'),
			amis()->SelectControl('bd_uid', '业务负责人')
				->searchable(true)
				->source('/system/admin_users?_action=getData')
				->labelField('name')
				->valueField('id'),
			
			amis()->TextareaControl('remark', '备注'),
		]);
	}


}